/**
 * @author roy
 * @desc   royui
 * @time   2022/04/29
 */
var royui = function () {
    this.v = '1.0.0';
};
var $config = null;
royui.prototype.render = function ($options) {
    $config = {
        elem: $options.elem ?? '#treeTable',    // 容器
        cols: $options.cols ?? undefined,    // 列参数
        url: $options.url ?? undefined,     // url模式
        method: $options.method ?? 'get',   // url请求方式
        where: $options.where ?? undefined,   // url 请求参数
        data: $options.data ?? undefined,    // 直接赋值数据
        tree: {
            primary_key: $options.tree ? ($options.tree.primary_key ?? 'id') : 'id',         // 主键名称
            iconIndex: $options.tree ? ($options.tree.iconIndex ?? 0) : 0,                // 图标列的索引
            icon: $options.tree ? ($options.tree.icon ?? '<div class="royui-icon-triangle-r"></div>') : ''          // 折叠图标
        },
        checkbox: $options.checkbox ?? false,                // 是否添加复选框
        callback: undefined,
        onSelected: undefined
    };
    if ($config.url && !$config.data) {
        $.ajax({
            type: $config.method, dataType: 'json', cache: false,
            async: false,
            url: $config.url,
            data: $config.where,
            success: function ($data) {
                $config.data = $data;
            },
            error: function () {
                throw '服务器异常';
            }
        })
    }
    if ($config.data === undefined || $config.data === null || $config.data === '' || $.type($config.data) !== 'array') {
        throw '数据异常';
    }
    if ($config.cols) {
        $thead = '<thead><tr>';
        if ($config.checkbox) {
            $thead += '<th style="width: 50px;"><input type="checkbox" onclick="new royui().checkAll(this)" /></th>';
        } else {
            $thead += '<th style="width: 15px;"></th>'
        }
        $($config.cols).each(function ($i, $col) {
            let $title_style = $col.title_style ? ' style="' + $col.title_style + '"' : '';
            $thead += '<th' + $title_style + '>' + $col.title + '</th>';
        });
        $thead += '</tr></thead>';
        $($config.elem).attr({'cellpadding': 0, 'cellspacing': 0}).addClass('royui-treetable').append($thead);
        $tbody = '<tbody>';
        $($config.data).each(function ($i, $item) {
            $tbody += '<tr>';
            if ($config.checkbox) {
                $tbody += '<td align="center"><input type="checkbox" class="royui_checkbox" value="' + $item[$config.tree.primary_key] + '" /></td>';
            } else {
                $tbody += '<td style="width: 15px;"></td>'
            }
            $($config.cols).each(function ($ii, $col) {
                let $icon = '', $hh = $item.has_children ?? false;
                if ($ii === $config.tree.iconIndex && $hh) {
                    $icon = $config.tree.icon;
                }
                $tbody += new royui().createCol($col, 0, $item, $icon, $config.tree.primary_key);
            });
            $tbody += '</tr>';
        });
        $tbody += '</tbody>';
        $($config.elem).append($tbody);
    }
};
royui.prototype.createCol = function ($col, $level, $v, $icon, $key_name, $indent = 0) {
    let $type = $col.type ?? 'normal', $class = $col.className ? ' class="' + $col.className + '"' : '', $style = $col.style ? ' style="' + $col.style : '';
    let $onclick = '', $onmouseover = '', $onmouseleave = '', $data_id = '', $data_tip = '';
    if ($icon !== '') {
        $onclick = ' onclick="new royui().clickTD(this, \'' + $key_name + '\', ' + ($level+1) + ')"';
        $data_id = ' data-' + $key_name + '="' + $v[$key_name] + '"';
        if ($v['tip']) {
            $data_tip = ' data-tip="' + $v['tip'] + '"';
            $onmouseover = ' onmouseover="new royui().mouseOver(this)"';
            $onmouseleave = ' onmouseleave="new royui().mouseLeave(this)"';
        }
        $style = $style ? $style + ';cursor:pointer' : ' style="cursor:pointer';
    }
    if ($level > 0 && $indent === 1) {
        $indent = 'text-indent:' + ($level * 12) + 'px;';
        $style = $style ? $style + ';' + $indent : ' style="' + $indent;
    }
    if ($style !== '') {
        $style += ';color:#3a6be0"';
    }
    let $str = '<td' + $data_id + $class + $style + $onclick + '>';
    if (typeof $col.template === "function") {
        $str += '<span' + $data_tip + $onmouseover + $onmouseleave + '>' + $icon + $col.template($v) + '</span>';
    } else if ($col.action) {
        $($col.action).each(function ($j, $acts) {
            let $act = $acts['matter'], $url = $acts['url'], $method = $acts['method'];
            let $data_url = '', $data_key = '', $data_area = '', $onclicka = '';
            if ($method && $method === 'popup') {
                $data_url = ' data-url="' + $url + '"';
                $data_key = ' data-' + $key_name + '="' + $v[$key_name] + '"';
                $data_area = ' data-area="' + ($acts['area'] ?? ['560px', '750px']) + '"';
                let $title = '';
                if ($act === 'edit' || $act === 'modify') {
                    $title = '编辑';
                } else if ($act === 'info' || $act === 'details') {
                    $title = '详情';
                } else if ($act === 'delete' || $act === 'del') {
                    $title = '删除';
                }
                $onclicka = ' onclick="new royui().clickA(this, \'' + $key_name + '\', \'' + $title + '\')"';
                $url = 'javascript:;';
            }
            if ($act === 'edit' || $act === 'modify') {
                $str += '<a href="' + $url + '"' + $data_url + $data_key + $data_area + $onclicka + ' class="royui-button-a">编辑</a> &nbsp; ';
            } else if ($act === 'delete' || $act === 'del') {
                $str += '<a href="' + $url + '"' + $data_url + $data_key + $data_area + $onclicka + ' class="royui-button-a">删除</a> &nbsp; ';
            } else if ($act === 'info' || $act === 'details') {
                $str += '<a href="' + $url + '"' + $data_url + $data_key + $data_area + $onclicka + ' class="royui-button-a">详情</a> &nbsp; ';
            }
        })
    } else if ($type === 'text') {
        $str += '<input type="text" value="' + ($v[$col.field]??'') + '" />';
    } else if ($type === 'select') {
        $str += '<select' + $class + $style + '>';
        $($v[$col.field]).each(function ($i, $o) {
            $check = '';
            if ($o.is_checked && $o.is_checked === 1) {
                $check = ' selected="1"';
            }
            $str += '<option value="' + $o.value + '"' + $check + '>' + $o.name + '</option>';
        });
        $str += '</select>';
    } else if ($type === 'checkbox') {
        $str += '<input type="checkbox" value="' + ($v[$col.field]??'') + '" />';
    } else if ($type === 'normal') {
        $str += '<span' + $data_tip + $onmouseover + $onmouseleave + '>' + $icon + ($v[$col.field]??'') + '</span>';
    }
    $str += '</td>';
    return $str;
};
royui.prototype.checkAll = function ($obj) {
    if ($($obj).is(':checked')) {
        $('.royui_checkbox').prop('checked', true);
    } else {
        $('.royui_checkbox').prop('checked', false);
    }
};
royui.prototype.clickTD = function ($obj, $param_name, $level) {
    let $div = $($obj).find('div'), $class = $div.attr('class');
    let $id = $($obj).data($param_name), $url = $config.url;
    let $children = $('tr[data-pid="' + $id + '"]');
    if ($class === 'royui-icon-triangle-r') {
        $div.attr('class', 'royui-icon-triangle-d');
        //$children.removeAttr('style');
    } else if ($class === 'royui-icon-triangle-d') {
        $div.attr('class', 'royui-icon-triangle-r');
        //$children.css('display', 'none');
        $children.remove();
    }
    if ($children.length > 0) {
        return false;
    }
    $param = {};
    $param[$param_name] = $id;
    $.ajax({
        type: $config.method, dataType: 'json', cache: false,
        url: $url,
        data: $param,
        success: function ($data) {
            let $str = '';
            $($data).each(function ($i, $item) {
                $str += '<tr data-pid="' + $id + '">';
                if ($config.checkbox) {
                    $str += '<td align="center"><input type="checkbox" class="royui_checkbox" value="' + $item[$config.tree.primary_key] + '" /></td>';
                } else {
                    $str += '<td style="width: 15px;"></td>'
                }
                $($config.cols).each(function ($ii, $col) {
                    let $icon = '', $hh = $item.has_children ?? false;
                    let $indent = 0;
                    if ($ii === $config.tree.iconIndex) {
                        $indent = 1;
                        if ($hh) {
                            $icon = $config.tree.icon;
                        }
                    }
                    $str += new royui().createCol($col, $level + 1, $item, $icon, $config.tree.primary_key, $indent);
                });
                $str += '</tr>';
            });
            $($obj).parent('tr').after($str);
        }
    })
};
royui.prototype.clickA = function ($obj, $param_name, $title) {
    let $id = $($obj).data($param_name), $url = $($obj).data('url');
    let $area = $($obj).data('area').split(',');
    let $param = {};
    $param[$param_name] = $id;
    if ($title === '详情') {
        layer.open({
            type: 2,
            title: $title,
            content: $url,
            area: $area,
            closeBtn: 2,
            btn: ['确定'],
            btn1: function ($index, $layero) {
                layer.close($index);
            }
        });
    } else if ($title === '编辑') {
        let $open = layer.open({
            type: 2,
            title: $title,
            content: $url,
            area: $area,
            closeBtn: 2,
            btn: ['确定', '取消'],
            yes: function ($index, $layero) {
                let $body = $layero.find('iframe').contents().find('body');
                let $param = $($body).find('form').serialize();
                $param = $param.split('&');
                let $params = [];
                $($param).each(function ($n, $obj) {
                    $params[$obj.split('=')[0]] = $obj.split('=')[1];
                });
                $.ajax({
                    type: 'post', dataType: 'json', cache: false,
                    url: $url,
                    data: $params,
                    success: function ($data) {
                        if (($data['status'] && $data['status'] == 0 || $data['status'] == 200) || ($data['code'] && $data['code'] == 0 || $data['code'] == 200)) {
                            layer.msg('修改成功', {icon: 1, time: 1200}, function(){
                                layer.close($open);
                                window.parent.location.reload();
                            });
                        } else {
                            layer.msg('修改失败', {icon: 5});
                        }
                    }
                })
            },
            btn2: function ($index, $layero) {
                layer.close($index);
            }
        });
    } else if ($title === '删除') {
        layer.confirm('确实要删除吗？', {icon: 3}, function () {
            $param['action'] = 'delete';
            $.ajax({
                type: $config.method, dataType: 'json', cache: false,
                url: $url,
                data: $param,
                success: function ($data) {
                    if (($data['status'] && $data['status'] == 0 || $data['status'] == 200) || ($data['code'] && $data['code'] == 0 || $data['code'] == 200)) {
                        layer.msg('删除成功', {icon: 1, time: 1200}, function(){
                            location.reload();
                        });
                    } else {
                        layer.msg('删除失败', {icon: 5});
                    }
                }
            });
        });
    }
};
var $tip = null;
royui.prototype.mouseOver = function ($obj) {
    let $msg = $($obj).data('tip');
    $tip = layer.tips($msg, $($obj), {tips: [2, '#b92'], time: -1});
}
royui.prototype.mouseLeave = function () {
    layer.close($tip);
}
$('head').append([
    '<style type="text/css">',
    '.royui-treetable{border:solid 1px #ddd;overflow:hidden;width:100%}',
    '.royui-treetable thead tr{background:#ddd;border:0;}',
    '.royui-treetable tbody tr:nth-of-type(even){background:#ececec;}',
    '.royui-treetable tbody tr:hover{background:#cfcfcf;}',
    '.royui-treetable th,.royui-treetable td{height:36px;}',
    '.royui-treetable td span{display:inline-block;}',
    '.royui-icon-triangle-u{width:0;height:0;display:inline-block;margin-right:5px;cursor:pointer;border-width:0 6px 6px;border-style:solid;border-color:transparent transparent #333;}/* 向上 */',
    '.royui-icon-triangle-d{width:0;height:0;display:inline-block;margin-right:5px;cursor:pointer;border-width:6px 6px 0;border-style:solid;border-color:#333 transparent transparent;}/* 向下 */',
    '.royui-icon-triangle-l{width:0;height:0;display:inline-block;margin-right:5px;cursor:pointer;border-width:6px 6px 6px 0;border-style:solid;border-color:transparent #333 transparent transparent;}/* 向左 */',
    '.royui-icon-triangle-r{width:0;height:0;display:inline-block;margin-right:5px;cursor:pointer;border-width:6px 0 6px 6px;border-style:solid;border-color:transparent transparent transparent #333;}/* 向右 */',
    '.royui-button-a{font-size:12px;text-decoration:none;color:#3a6be0;}',
    '</style>'
].join(''));